package com.th.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.th.common.domain.UsInternalMessage;
import com.th.common.exception.BaseServiceException;
import com.th.common.mybatis.query.LambdaQueryWrapperX;
import com.th.common.response.PageResult;
import com.th.mapper.UsInternalMessageMapper;
import com.th.service.UsInternalMessageService;
import com.th.service.UsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author ErrorRua
 * @date 2023/06/25
 * @description:
 */
@Service
public class UsInternalMessageServiceImpl extends ServiceImpl<UsInternalMessageMapper, UsInternalMessage> implements UsInternalMessageService {

    @Autowired
    private UsUserService usUserService;

    @Override
    public PageResult<UsInternalMessage> page(Integer currentPage, Integer size) {

        IPage<UsInternalMessage> page = new Page<>(currentPage, size);

        LambdaQueryWrapper<UsInternalMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UsInternalMessage::getUserId, usUserService.getCurrentUserId())
                .select(UsInternalMessage::getId, UsInternalMessage::getUserId, UsInternalMessage::getMessageTitle,
                        UsInternalMessage::getMessageType, UsInternalMessage::getStatus, UsInternalMessage::getCreateTime)
                .orderByDesc(UsInternalMessage::getCreateTime);
        page = page(page, queryWrapper);

        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    @Override
    public UsInternalMessage getMessageDetail(Long id) {
        UsInternalMessage message = getById(id);
        if (checkMessageExist(message)) {
            throw new BaseServiceException(4004, "消息不存在");
        }

        // 如果消息未读，则更新为已读
        if (message.getStatus() == 0) {
            message.setStatus((short) 1);
            updateById(message);
        }

        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void read(List<Long> ids) {
        List<UsInternalMessage> messages = listByIds(ids);
        if (messages.size() != ids.size()) {
            throw new BaseServiceException(4004, "消息不存在");
        }

        messages.forEach(message -> {
            if (message.getStatus() == 0) {
                message.setStatus((short) 1);
            }
        });

        updateBatchById(messages);
    }

    private boolean checkMessageExist(UsInternalMessage message) {
        return Objects.isNull(message) || !message.getUserId().equals(usUserService.getCurrentUserId());
    }

}
